package com.example.zyl.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {


    public static void compressFiles(List<String> fileUrls, HttpServletResponse response) {
        // 压缩文件
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (String fileUrl : fileUrls) {
                // 从网络下载文件并写入 ZIP
                try {
                    URL url = new URL(fileUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();

                    // 检查响应码
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                        throw new IOException("Failed to download file: " + fileUrl);
                    }

                    // 创建 ZIP 条目
                    ZipEntry zipEntry = new ZipEntry(getFileNameFromUrl(fileUrl));
                    zipOut.putNextEntry(zipEntry);

                    // 读取文件的输入流
                    try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = inputStream.read(buffer)) >= 0) {
                            zipOut.write(buffer, 0, length);
                        }
                    }
                    zipOut.closeEntry();
                } catch (IOException e) {
                    System.err.println("Error processing file URL: " + fileUrl + " - " + e.getMessage());
                }
            }
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=test.zip");
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private static String getFileNameFromUrl(String fileUrl) {
        // 从 URL 中提取文件名
        return fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
    }
}
